package com.basin.common.feign.interceptor;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.util.ObjUtil;
import com.basin.common.core.exception.BasinAssert;
import com.basin.common.feign.properties.BasinBasicProp;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Slf4j
@RequiredArgsConstructor
public class FeignRequestInterceptor implements RequestInterceptor {
    private final BasinBasicProp basinBasicProp;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取目标服务名
        String serviceName = requestTemplate.feignTarget().name();
        BasinBasicProp.Account account = basinBasicProp.getBasic().get(serviceName);
        BasinAssert.isTrue(ObjUtil.isNotNull(account), "未配置服务[%s]的登录信息".formatted(serviceName));
        String username = account.getUsername();
        String password = account.getPassword();
        String authHeader = buildAuthHeader(username, password);
        requestTemplate.header("Authorization", authHeader);
    }

    /**
     * 构造Auth请求头
     */
    private String buildAuthHeader(String username, String password) {
        String auth = username + ":" + password;
        return "Basic " + Base64Encoder.encode(auth);
    }

}
